package com.cnd.scm.rabbitmq.common;

import com.cnd.scm.redis.cache.util.RedisUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @version V1.0
 * @ClassName: RedisMessageSender
 * @Description:
 * @author: 李启联
 * @date: 2021-03-22 10:10
 * @Copyright: Copyright (c), 2021
 */
@Service
public class RedisMessageSender implements MessageSender {

    private static final String MESSAGE_SENDER_kEY = "message.sender.key";

    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 向发送消息容器增加要发送的消息
     *
     * @param messageLog
     */
    @Override
    public void storeMessage(MessageLog messageLog) {
        //redisUtil.hmSet(MESSAGE_SENDER_kEY, messageLog.getId(), messageLog);
    }

    /**
     * 更新保存在容器中投递消息的状态
     *
     * @param status 消息状态
     * @param msgId  消息ID
     */
    @Override
    public void updateStatus(MessageStatusEnum status, String msgId) {

    }

    /**
     * 删除发送容器中的一条消息
     *
     * @param id
     */
    @Override
    public void delMessage(String id) {
        redisUtil.hmdDelete(MESSAGE_SENDER_kEY,id);
    }

    /**
     * 发送消息
     *
     * @param message
     * @return
     */
    @Override
    public DetailResponse send(Object message) {
        String id = UUID.randomUUID().toString().replace("-","").toUpperCase();
        return null;//send(new MessageLog(id, message,rabbitTemplate.getExchange(),rabbitTemplate.getRoutingKey()));
    }

    /**
     * 发送消息
     *
     * @param messageLog
     * @return
     */
    @Override
    public DetailResponse send(MessageLog messageLog) {
        try {
            storeMessage(messageLog);
//            rabbitTemplate.correlationConvertAndSend(messageLog.getMessage(), new CorrelationData(String.valueOf(messageLog.getId())));
//            messageLog.setStatus(1);
            storeMessage(messageLog);
        } catch (Exception e) {
            //messageLog.setStatus(2);
            storeMessage(messageLog);
            return new DetailResponse(false, "", "");
        }
        return new DetailResponse(true, "", "");
    }

    /**
     * 开启重试发送机制
     */
    @Override
    public void retry() {

    }
}